package me.yuzho.study;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
import java.util.concurrent.TimeUnit;

/** 利用WatchService监控目录下文件的变化
 * @author yzhou-citrix
 *
 */
public class FoldWatcher {

    public static void main(String[] args) {
        Path myDir = Paths.get("/Users/yzhou-citrix/test");  
        
        try {
            WatchService watcher = myDir.getFileSystem().newWatchService();
            
            myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE,
                    StandardWatchEventKinds.ENTRY_MODIFY);
            
            while(true) {
                
                
                
                WatchKey watchKey = watcher.poll(5, TimeUnit.SECONDS);//watcher.take();
                
                if(watchKey == null) {
                    System.out.println("loop for next watch...");
                    continue;
                }
                
                List<WatchEvent<?>> events = watchKey.pollEvents();
            
                for(WatchEvent<?> event: events) {
                    
                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("Created: " + event.context().toString());
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("Delete: " + event.context().toString());
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("Modify: " + event.context().toString());
                    }   
                }
                
                watchKey.reset();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
